#include "web_app.h"
#include "esp_sntp.h"
#include "http_flie_server.h"
#include "time_sntp_driver.h"
#include "camera_driver.h"
#include "fatfs_driver.h"
#include "szp_hardware_driver.h"
#include "web_server_driver.h"
#include "my_ui_api.h"
#include "actions.h"
#include "ui.h"
#include "screens.h"
#include "vars.h"
#include "fonts.h"
#include "styles.h"

static const char *TAG = "web_app";

TaskHandle_t task_wifi_scan_handle = NULL;

void refresh_wifi_list()
{
    uint16_t sta_number = 0;
    wifi_ap_record_t *ap_list_buffer;
    esp_wifi_scan_start(NULL, true);
    esp_wifi_scan_get_ap_num(&sta_number);
    if (!sta_number)
    {
        ESP_LOGE(TAG, "No AP found");
        return;
    }

    ap_list_buffer = malloc(sta_number * sizeof(wifi_ap_record_t));
    if (ap_list_buffer == NULL)
    {
        ESP_LOGE(TAG, "Failed to malloc buffer to print scan results");
        esp_wifi_clear_ap_list();
        return;
    }

    if (esp_wifi_scan_get_ap_records(&sta_number, (wifi_ap_record_t *)ap_list_buffer) == ESP_OK)
    {
        extern lv_indev_t *disp_indev;
        lv_indev_enable(disp_indev, false);
        lvgl_port_lock(0);
        lv_obj_clean(objects.wifi_list);
        lvgl_port_unlock();
        for (int i = 0; i < sta_number; i++)
        {
            lvgl_port_lock(0);
            add_wifi_panel(ap_list_buffer[i].rssi, (char *)ap_list_buffer[i].ssid, ap_list_buffer[i].authmode != WIFI_AUTH_OPEN);
            lvgl_port_unlock();
            vTaskDelay(pdMS_TO_TICKS(50));
        }
        lv_indev_enable(disp_indev, true);
    }
    free(ap_list_buffer);
}

void wifi_select_cb(lv_event_t *e)
{
    const char *ssid = (const char *)lv_event_get_user_data(e);
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_DELETE)
    {
        ESP_LOGI(TAG, "delete list %d", ssid);
        lv_mem_free(ssid);
    }

    if (code == LV_EVENT_CLICKED)
    {
        // extern TaskHandle_t *task_wifi_scan_handle;
        // vTaskDelete(task_wifi_scan_handle);
        eez_flow_set_screen(SCREEN_ID_WIFI_CONNECT_PAGE_2, LV_SCR_LOAD_ANIM_FADE_ON, 200, 0);
        ESP_LOGI(TAG, "select wifi ssid = %s", ssid);
        lv_label_set_text(objects.wlan_name_label, ssid);
    }
}

// static void time_sync_notification_cb(struct timeval *tv)
// {
//     close_spinner();
//     eez_flow_set_screen(SCREEN_ID_SHOW_SNTP_TIME_PAGE, LV_SCR_LOAD_ANIM_FADE_ON, 200, 0);
//     save_time_into_file();
// }

void task_sntp(void *arg)
{
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    esp_sntp_setservername(0, "ntp1.aliyun.com"); // 阿里云 NTP 服务器
    esp_sntp_setservername(1, "cn.pool.ntp.org"); // 中国 NTP 服务器
    esp_sntp_setservername(2, "pool.ntp.org");    // 默认服务器

    // 注册时间同步回调函数
    // sntp_set_time_sync_notification_cb(time_sync_notification_cb);

    esp_sntp_init();
    setenv("TZ", "CST-8", 1);
    tzset();
    close_spinner();
    eez_flow_set_screen(SCREEN_ID_SHOW_SNTP_TIME_PAGE, LV_SCR_LOAD_ANIM_FADE_ON, 200, 0);
    vTaskDelete(NULL);
}

void wifi_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED)
    {
        ESP_LOGI(TAG, "CONNECTED");

        xTaskCreatePinnedToCore(task_sntp, "task_sntp", 4096, NULL, 4, NULL, 1);
        web_server_init();

        wifi_ip_got_state = false;
    }
    else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
    {
        ESP_LOGI(TAG, "DISCONNECTED to wifi SSID:%s ,password:%s", STA_SSID, STA_PASSWORD);
        wifi_ip_got_state = false;
        esp_wifi_connect();
    }
    else if (event_id == WIFI_EVENT_AP_STACONNECTED)
    {
        wifi_event_ap_staconnected_t *event = (wifi_event_ap_staconnected_t *)event_data;
        ESP_LOGI(TAG, "station " MACSTR " join, AID=%d", MAC2STR(event->mac), event->aid);
    }
    else if (event_id == WIFI_EVENT_AP_STADISCONNECTED)
    {
        wifi_event_ap_stadisconnected_t *event = (wifi_event_ap_stadisconnected_t *)event_data;
        ESP_LOGI(TAG, "station " MACSTR " leave, AID=%d", MAC2STR(event->mac), event->aid);
    }
}

void wifi_event_STA_GOT_IP_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
    {
        ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
        uint16_t wifi_ip_addr[4];
        wifi_ip_addr[0] = esp_ip4_addr1_16(&event->ip_info.ip);
        wifi_ip_addr[1] = esp_ip4_addr2_16(&event->ip_info.ip);
        wifi_ip_addr[2] = esp_ip4_addr3_16(&event->ip_info.ip);
        wifi_ip_addr[3] = esp_ip4_addr4_16(&event->ip_info.ip);
        wifi_ip_got_state = true;
        char str[25];
        sprintf(str, "请打开%d.%d.%d.%d网址查看相册", wifi_ip_addr[0], wifi_ip_addr[1], wifi_ip_addr[2], wifi_ip_addr[3]);
        ESP_LOGI(TAG, "请打开%d.%d.%d.%d网址查看相册", wifi_ip_addr[0], wifi_ip_addr[1], wifi_ip_addr[2], wifi_ip_addr[3]);
        lvgl_port_lock(0);
        lv_label_set_text(objects.http_server_prompt_label, str);
        lvgl_port_unlock();
    }
}

void task_wifi_scan(void *arg)
{
    lvgl_port_lock(0);
    lv_obj_clear_flag(objects.spinner_1, LV_OBJ_FLAG_HIDDEN);
    eez_flow_set_screen(SCREEN_ID_WIFI_CONNECT_PAGE, LV_SCR_LOAD_ANIM_FADE_ON, 200, 0);
    lvgl_port_unlock();

    wifi_mode_t current_mode;
    if (esp_wifi_get_mode(&current_mode) == ESP_ERR_WIFI_NOT_INIT)
    {
        wifi_init(WIFI_MODE_STA, true);
    }
    vTaskDelay(10);

    lvgl_port_lock(0);
    lv_obj_add_flag(objects.spinner_1, LV_OBJ_FLAG_HIDDEN);
    lvgl_port_unlock();

    while (1)
    {
        refresh_wifi_list();
        vTaskDelay(pdMS_TO_TICKS(2000));
        vTaskDelay(pdMS_TO_TICKS(2000));
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

void web_task_start()
{
    multi_heap_info_t info;
    heap_caps_get_info(&info, MALLOC_CAP_INTERNAL);
    ESP_LOGI(TAG, "Internal RAM: total=%d, free=%d, largest=%d",
             info.total_allocated_bytes, info.total_free_bytes, info.largest_free_block);
        xTaskCreatePinnedToCore(task_wifi_scan, "task_wifi_scan", 4096 * 5, NULL, 4, &task_wifi_scan_handle, 1);
}